package cn.arifun.manage;

import cn.arifun.entity.SysUser;
import cn.arifun.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @Author: 漆原
 * @Description: 系统用户管理
 * @DateTime: 2024/10/1 15:24
 **/
@Component
public class SysUserManage implements UserDetailsManager, UserDetailsPasswordService {
    @Resource
    private SysUserMapper userMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        SysUser sysUser = new SysUser();
        sysUser.setName(user.getUsername());
        sysUser.setPassword(user.getPassword());
        sysUser.setEnable(user.isEnabled());
        userMapper.insert(sysUser);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        SysUser sysUser = userMapper.selectOne(queryWrapper);
        if (sysUser == null)
            throw new UsernameNotFoundException(username);

        return new User(sysUser.getName(),
                sysUser.getPassword(),
                sysUser.getEnable(),
                true,//账号是否过期
                true,//凭证是否过期
                true,//是否被锁定
                new ArrayList<>());//权限列表
    }
}
